<template>
    <div class="containter">
        <div>
            <el-card>
                <filterComponent v-model:filter-data="filterData" @doSearch="handleSearch"/>
            </el-card>
        </div>
        <el-card class="mg-t-20">
            <tableComponent class="set-height w-full" :table-header="tableHeader" :table-data="tableData"
                            v-model:page-info="pageInfo" @pageChange="handlePageChange">
                <template #index>
                    <el-table-column type="expand">
                        <template #default="props">
                            <div class="w-full box-border flex gap-8px p-16px">
                                <div class="flex-1 flex flex-column gap-8">
                                    <div class="text-center font-bold text-24px">公司白名单</div>
                                    <div class="flex gap-8px w-full items-center">
                                        <div class="w-200px text-end flex-shrink-0">公司：</div>
                                        <el-select clearable filterable multiple remote
                                                   v-model="tableDataInner[props.$index].needAddCompanyWhitelist"
                                                   :max-collapse-tags="2" collapse-tags-tooltip collapse-tags
                                                   reserve-keyword value-key="companyId"
                                                   placeholder="请选择公司" :remote-method="remoteMethod"
                                                   @change="changeCompanyName(props.$index)"
                                                   :loading="loading">
                                            <el-option v-for="item in companylist" :key="item.companyId"
                                                       :label="item.companyName" :value="item"/>
                                        </el-select>
                                    </div>
                                    <div class="flex gap-8px w-full items-center"
                                         v-if="tableDataInner[props.$index].companyWhitelist.length!==0">
                                        <div class="w-200px text-end flex-shrink-0">已选公司：</div>
                                        <div class="flex-1">
                                            <ul class="infinite-list" style="overflow: auto">
                                                <li v-for="(item,i) in tableDataInner[props.$index].companyWhitelist"
                                                    :key="i"
                                                    class="infinite-list-item">
                                                    <div>
                                                        {{ item.companyName }}
                                                    </div>
                                                    <el-button size="small" type="danger"
                                                               @click="delCompanyWhite(props.$index,item,i)"
                                                               :icon="Delete" circle/>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex-1 flex flex-column gap-8">
                                    <div class="text-center font-bold text-24px">派遣单位白名单</div>
                                    <div class="flex gap-8px w-full items-center">
                                        <div class="w-200px text-end flex-shrink-0">派遣单位：</div>
                                        <el-select clearable filterable multiple remote
                                                   v-model="tableDataInner[props.$index].needAddServiceCompanyWhitelist"
                                                   :max-collapse-tags="2" collapse-tags-tooltip collapse-tags
                                                   reserve-keyword value-key="companyId"
                                                   placeholder="请选择派遣单位" :remote-method="remoteMethodServiceCompany"
                                                   @change="changeServiceCompanyName(props.$index)"
                                                   :loading="loading">
                                            <el-option v-for="item in serviceCompanylist" :key="item.companyId"
                                                       :label="item.companyName" :value="item"/>
                                        </el-select>
                                    </div>
                                    <div class="flex gap-8px w-full items-center"
                                         v-if="tableDataInner[props.$index].serveCompanyWhitelist.length!==0">
                                        <div class="w-200px text-end flex-shrink-0">已选派遣单位：</div>
                                        <div class="flex-1">
                                            <ul class="infinite-list" style="overflow: auto">
                                                <li v-for="(item,i) in tableDataInner[props.$index].serveCompanyWhitelist"
                                                    :key="i"
                                                    class="infinite-list-item">
                                                    <div>
                                                        {{ item.companyName }}
                                                    </div>
                                                    <el-button size="small" type="danger"
                                                               @click="delServiceCompanyWhite(props.$index,item,i)"
                                                               :icon="Delete" circle/>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="flex items-center justify-center">
                                <el-button size="large" type="primary" @click="onSure(tableDataInner[props.$index])">
                                    确定修改
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template #name>
                    <el-table-column label="保司名称" prop="name">
                        <template #default="scope">
                            {{
                                mapName.find((ele, i) => {
                                    return ele.dictValue === scope.row.insurCompany
                                })?.dictLabel
                            }}
                        </template>
                    </el-table-column>
                </template>
                <template #operate>
                    <el-table-column fixed="right" label="操作" width="120">
                        <template #default="scope">
                            <el-button link type="danger" size="small" @click="handleRemove(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </template>
            </tableComponent>
        </el-card>
    </div>
    <addInsureWhiteList v-model:show="showAdd" @success="onAddSusccess"/>
</template>
<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {Delete} from '@element-plus/icons-vue'
import filterComponent from '@/components/filterComponent/index.vue'
import tableComponent from '@/components/tableComponent/index.vue'
import addInsureWhiteList from './components/dialog/addInsureWhiteList.vue'
import {
    deleteInsurRegionRestrictionWhitelistApi,
    editInsurRegionRestrictionWhitelistApi,
    getInsureComponyList,
    getQueryInsurRegionRestrictionWhitelistApi,
    addInsurRegionRestrictionWhitelistApi
} from "@/api/insure/longTerm";
import {getpassedcompanyapi, queryServeCompanyListApi} from "@/api/api";

const loading = ref(false)
const companylist = ref([])
const serviceCompanylist = ref([])
const delCompanyWhite = (i, item, innerIndex) => {
    if (item.fromAdd) {
        tableDataInner.value[i].needAddCompanyWhitelist = tableDataInner.value[i].needAddCompanyWhitelist.filter(ele => {
            return ele.companyId !== item.companyId
        })
        changeCompanyName(i)
    } else {
        tableDataInner.value[i].companyWhitelist.splice(innerIndex, 1)
        tableDataInner.value[i].copyCompanyWhitelist.splice(innerIndex, 1)
    }

}
const delServiceCompanyWhite = (i, item, innerIndex) => {
    if (item.fromAdd) {
        tableDataInner.value[i].needAddServiceCompanyWhitelist = tableDataInner.value[i].needAddServiceCompanyWhitelist.filter(ele => {
            return ele.companyId !== item.companyId
        })
        changeServiceCompanyName(i)
    } else {
        tableDataInner.value[i].serveCompanyWhitelist.splice(innerIndex, 1)
        tableDataInner.value[i].copyServiceCompanyWhitelist.splice(innerIndex, 1)
    }

}
const changeCompanyName = (i) => {
    let arr = []
    tableDataInner.value[i].needAddCompanyWhitelist.forEach(ele => {
        arr.push({companyId: ele.id, companyName: ele.companyName, fromAdd: true})
    })
    tableDataInner.value[i].companyWhitelist = tableDataInner.value[i].copyCompanyWhitelist.concat(arr)
}
const changeServiceCompanyName = (i) => {
    let arr = []
    tableDataInner.value[i].needAddServiceCompanyWhitelist.forEach(ele => {
        arr.push({companyId: ele.companyId, companyName: ele.companyName, fromAdd: true})
    })
    tableDataInner.value[i].serveCompanyWhitelist = tableDataInner.value[i].copyServiceCompanyWhitelist.concat(arr)
}
const remoteMethod = (query) => {
    if (query) {
        loading.value = true
        getCompany(query)
    } else {
        companylist.value = []
    }
}
// 获取公司列表
const getCompany = async (val) => {
    companylist.value = await getpassedcompanyapi({companyName: val, auditStatus: 1})
    companylist.value.forEach((i) => {
        i.companyId = i.id
    })
    loading.value = false
}
const remoteMethodServiceCompany = (query) => {
    if (query) {
        loading.value = true
        getServiceCompany(query)
    } else {
        serviceCompanylist.value = []
    }
}
// 获取派遣单位列表
const getServiceCompany = async (val) => {
    serviceCompanylist.value = await queryServeCompanyListApi({serveCompanyName: val})
    serviceCompanylist.value.forEach((i) => {
        i.companyId = i.serveCompanyId
        i.companyName =
            i.serveCompanyName + '(' + i.companyName + ')'
    })
    loading.value = false
}
const filterData = ref({
    list: {
        insurCompany: {
            name: '保司',
            prop: 'insurCompany',
            value: '',
            placeholder: '请选择保司',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'dictLabel',
                value: 'dictValue'
            },
            handleFocus: (item) => {
                if (item.options?.length) return
                getInsureComponyList().then(res => {
                    item.options = res
                })
            }
        },
    },
    buttonList: [
        {
            icon: 'Plus',
            name: '新增',
            click: () => {
                showAdd.value = true
            }
        }
    ]
})

const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const tableHeader = ref([
    {
        label: '序号',
        prop: 'index',
        width: 100
    },
    {
        label: '保司名称',
        prop: 'name',
    },
    {
        label: '保司编码',
        prop: 'insurCompany',
    },
    {
        label: '操作',
        prop: 'operate',
    }
])

const showAdd = ref(false)
const mapName = ref([])
const tableData = ref([])
const tableDataInner = ref([])
const onAddSusccess = async (val) => {
    let obj = JSON.parse(JSON.stringify({
        companyWhitelist: val.companyWhitelist,
        serveCompanyWhitelist: val.serveCompanyWhitelist,
        id: val.id,
        insurCompany: val.insurCompany,
    }))
    if (obj.companyWhitelist.length === 0) {
        obj.companyWhitelist = null
    }
    if (obj.serveCompanyWhitelist.length === 0) {
        obj.serveCompanyWhitelist = null
    }
    addInsurRegionRestrictionWhitelistApi(obj).then(res => {
        ElMessage.success({
            message: '新增成功'
        })
        getList()
    })
}
const handleSearch = () => {
    getList()
}
const onSure = (val) => {
    let obj = JSON.parse(JSON.stringify({
        companyWhitelist: val.companyWhitelist,
        serveCompanyWhitelist: val.serveCompanyWhitelist,
        id: val.id,
        insurCompany: val.insurCompany,
        userName: val.userName,
    }))
    obj.companyWhitelist.forEach((i) => {
        delete i.fromAdd
    })
    obj.serveCompanyWhitelist.forEach((i) => {
        delete i.fromAdd
    })
    if (obj.companyWhitelist.length === 0 && obj.serveCompanyWhitelist.length === 0) {
        ElMessage.error('请选择公司或派遣单位')
        return;
    }
    if (obj.companyWhitelist.length === 0) {
        obj.companyWhitelist = null
    }
    if (obj.serveCompanyWhitelist.length === 0) {
        obj.serveCompanyWhitelist = null
    }
    editInsurRegionRestrictionWhitelistApi(obj).then(res => {
        ElMessage.success({
            message: '修改成功'
        })
        getList()
    })
}
const handlePageChange = () => {
    getList()
}

const createQuery = () => {
    const data = {}
    for (const key in filterData.value.list) {
        data[filterData.value.list[key].prop] = filterData.value.list[key].value
    }
    return data
}
const getList = async () => {
    let res = await getQueryInsurRegionRestrictionWhitelistApi({
        ...createQuery(),
        pageNum: pageInfo.value.pageNum,
        pageSize: pageInfo.value.pageSize
    })
    tableData.value = res.list
    tableDataInner.value = JSON.parse(JSON.stringify(res.list))
    tableDataInner.value.forEach((item, index) => {
        if (!item.companyWhitelist) {
            item.companyWhitelist = []
        }
        if (!item.serveCompanyWhitelist) {
            item.serveCompanyWhitelist = []
        }
        item.needAddServiceCompanyWhitelist = []
        item.needAddCompanyWhitelist = []
        item.copyCompanyWhitelist = item.companyWhitelist
        item.copyServiceCompanyWhitelist = item.serveCompanyWhitelist
    })
    pageInfo.value.total = res.total
}
const handleRemove = (item) => {
    ElMessageBox.confirm(
        `是否确认删除?`,
        '提示',
        {
            type: 'warning',
        }
    )
        .then(() => {
            deleteInsurRegionRestrictionWhitelistApi({
                id: item.id
            }).then(res => {
                ElMessage.success({
                    message: '删除成功'
                })
                getList()
            })
        })
}

onMounted(async () => {
    await getList()
    await getInsureComponyList().then(res => {
        mapName.value = res
    })
})
</script>
<style lang="scss" scoped>
.containter {
    padding: 16px;
}

.infinite-list {
    min-height: 10px;
    height: 150px;
    padding: 0;
    margin: 0;
    list-style: none;
}

.infinite-list .infinite-list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    height: 50px;
    background: var(--el-color-primary-light-9);
    margin: 10px;
    color: var(--el-color-primary);
}

.infinite-list .infinite-list-item + .list-item {
    margin-top: 10px;
}
</style>
